# -*- coding: UTF-8 -*-
from flask import Flask, request, jsonify, Blueprint
import oss2

from applications.common.utils.response_data import response_success

bp = Blueprint('file', __name__, url_prefix='/file')


auth = oss2.Auth('LTAI5tJ8KHDWVY6v3MDmojqV', '0qDNIy1yPnTC6N6oAB75oiQMuj85ok')
bucket = oss2.Bucket(auth,'oss-cn-hangzhou.aliyuncs.com', 'voicequan')

#处理跨域请求
# 处理跨域请求
@bp.after_request  # flask装饰器
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response


#上传文件接口
@bp.post('/upload')
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'please select file'})
    if file:
        filename = file.filename
        # 指定上传到OSS的目录，这里根据自己事情情况写
        oss_path = 'front/' + filename

        # 获取文件大小
        file_size = len(file.read())
        file.seek(0)

        #上传文件，并返回上传进度
        def percentage(consumed_bytes,total_bytes):
            if total_bytes:
                percentage = int(100 * (consumed_bytes / total_bytes))
                return jsonify({'progress': percentage})

        bucket.put_object(oss_path,file,progress_callback=percentage)

        #生成分享链接
        share_link= bucket.sign_url('GET',oss_path,60*60) #有效期一小时，我本来想用的 但是后来发现生成的链接带了明文的key和KeySecret，所以我在前端做了一个拼接
        return response_success(data=share_link)
